
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse }  from '@ohos/axios'
import { promptAction } from '@kit.ArkUI'

class BaseRequest {
  instance: AxiosInstance;

  constructor(config: AxiosRequestConfig<AxiosResponse>) {
    this.instance = axios.create(config);

    // 请求拦截
    this.instance.interceptors.request.use((config) => {
      // const token = '获取自己本地储存的token';
      // if (token) {
      //   config.headers.token = token;
      // }
      // console.log('Request config', config);
      return config;
    }, (err) => {
      console.error('Request error', err);
      return Promise.reject(err);
    }
    );

    // 响应拦截
    this.instance.interceptors.response.use((response: AxiosResponse<any, any>) => {
      let data = response.data;
      //本次测试接口没有状态码
      return data
      console.log('Response data', data);
      if (typeof data === 'string') {
        data = JSON.parse(data.trim());
      }
      const { code, msg } = data;
      if (code === 200) {  // 处理成功情况
        return response.data;
      } else if (code === 400) { // 处理错误码
        promptAction.showToast({
          message: msg
        });
        return Promise.reject(new Error(msg));
      } else if (code === 500) {
        promptAction.showToast({
          message: msg
        });
        return response.data;
      } else { // 处理其他错误码
        promptAction.showToast({
          message: msg
        });
        return Promise.reject(new Error(msg));
      }
    }, (err) => {
      console.error('Response error', err);
      return Promise.reject(err);
    }
    );
  }

  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    // console.log('Request config', config);
    return this.instance.request<any, T>({ ...config });
  }

  get<T = any>(url:string,config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'GET',url });
  }

  post<T = any>(url:string,config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'POST',url });
  }
  put<T = any>(url:string,config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'PUT',url });
  }
  delete<T = any>(url:string,config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE',url });
  }
}

export const http = new BaseRequest({
  // baseURL: 'http://10.28.60.70:3000',
  baseURL: 'http://172.18.0.33:3000',
  timeout: 60000
})
